package cliente;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Timestamp;

import cliente.GUI.InterfaceGrafica;

public class CloudStorage {
	private static ClientConfig configuracoes = null;
	private static SocketClient conexaoCliente = null;
	private static InterfaceGrafica interfaceGrafica = new InterfaceGrafica();
	private static DiretorioAssistido diretorioAssistido;
	
	public static void main(String[] args) {
		configuracoes = new ClientConfig();
		
		System.setProperty("javax.net.ssl.trustStore", configuracoes.getKeyStoreFile());
		System.setProperty("javax.net.ssl.trustStorePassword", configuracoes.getKeyStorePass());
		
		conexaoCliente = new SocketClient(configuracoes.getHost(), configuracoes.getServerPort());
	    Thread threadCliente = new Thread(conexaoCliente);
	    threadCliente.start();
	    
		diretorioAssistido = new DiretorioAssistido(true);
		Thread threadDiretorio = new Thread(diretorioAssistido);
		threadDiretorio.start();
		
		conexaoCliente.autenticacao(configuracoes.getUser(), configuracoes.getPassword());
		
		Synchronize sincronizar = new Synchronize();
		Thread threadSync = new Thread(sincronizar);
		threadSync.start();
	}
	
	public static ClientConfig getConfig(){
		return configuracoes;
	}
	
	public static SocketClient getConexaoCliente(){
		return conexaoCliente;
	}
	
	public static InterfaceGrafica getInterfaceGrafica(){
		return interfaceGrafica;
	}
	
	public static DiretorioAssistido getDiretorioAssistido(){
		return diretorioAssistido;
	}
	
	public static void updateCSFile(){
		File cloudStorageFile = new File(CloudStorage.getConfig().getDirectory() + ".synctime.csfile");

		Timestamp nowTime = new Timestamp(System.currentTimeMillis());
		
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(cloudStorageFile.getCanonicalFile());
			
			Writer writer = new BufferedWriter(new OutputStreamWriter(fos));
			
			writer.write(""+nowTime.getTime()+"");
			writer.close();
		} catch (FileNotFoundException e) {
			System.out.println("CloudStorage Error: " + e.toString());
		} catch (IOException e) {
			System.out.println("CloudStorage Error: " + e.toString());
		}
	}
	
	public static Timestamp getLastSyncTime(){
		File cloudStorageFile = new File(CloudStorage.getConfig().getDirectory() + ".synctime.csfile");
		
		String linha = "0";
		
		if(!cloudStorageFile.exists())
			return new Timestamp(0);
		
		try {
			FileReader fr = new FileReader(cloudStorageFile);
			LineNumberReader linhaLeitura = new LineNumberReader(fr);
			
			linha = linhaLeitura.readLine();
			
			fr.close();
			linhaLeitura.close();
		} catch (IOException e) {
			System.out.println("CloudStorage Error: " + e.toString());
		}

		return new Timestamp(Long.valueOf(linha));
	}
}
